<template>
    <div>
      <!--返回顶部-->
      <van-button v-if="btnFlag" icon="back-top" type="primary" @click="backTop" />
    </div>
  </template>
  
  <script>
  export default {
    name: 'BackTop',
    data () {
      return {
        btnFlag: false // 默认按钮不显示
      }
    },
    // vue的两个生命钩子，这里不多解释。
    // window对象，所有浏览器都支持window对象。它表示浏览器窗口，监听滚动事件
    mounted () {
      window.addEventListener('scroll', this.scrollToTop)
    },
    // 页面离开，取消addEventListener，不然页面会报错
    destroyed () {
      window.removeEventListener('scroll', this.scrollToTop)
    },
    methods: {
      // 点击图片回到顶部方法，加计时器是为了过渡顺滑
      backTop () {
        const that = this
        const timer = setInterval(() => {
          const ispeed = Math.floor(-that.scrollTop / 5)
          document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
          if (that.scrollTop === 0) {
            clearInterval(timer)
          }
        }, 16)
      },
      // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
      scrollToTop () {
        const that = this
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        that.scrollTop = scrollTop
        if (that.scrollTop > 0) {
          that.btnFlag = true
        } else {
          that.btnFlag = false
        }
      }
    }
  }
  </script>
  
  <style lang="less" scoped>
  .van-button{
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: none;
    background-color: rgba(0, 0, 0, .5);
    position: fixed;
    right: 10px;
    bottom: 60px;
    z-index: 5;
  }
  </style>
  